// sUndefined = require('lodash/isUndefined')
const isNumber = require('lodash/isNumber')
const cloud = require('wx-server-sdk')
const appid = process.env.appid //你的小程序appid
const secret = process.env.secretkey //你的小程序secret

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const ERROR_MSG = {
  500: '服务器错误',
  401: '登录过期',
  404: '未找到资源',
  4001: '重复提交'
}
class CustomError extends Error {
  constructor(code, msg) {
    super()
    this.code = code || 500
    this.msg = msg || ERROR_MSG[code] || 'unknown error'
  }
  getCodeMsg() {
    return {
      code: this.code,
      msg: this.msg
    }
  }
}
// 增加额外command功能
const _ = db.command
// 1. 获取数据库引用
const TcbRouter = require('tcb-router')

exports.main = async (event, context) => {
  const app = new TcbRouter({ event })
  const { OPENID, UNIONID } = cloud.getWXContext()
  app.use(async (ctx, next) => {
    //适用于所有的路由
    ctx.data = {} //声明data为一个对象
    try {
      ctx.body = {}
      ctx.body.code = 0
      await next()
    } catch (err) {
      console.log(err, 'err'.repeat(10))
      console.log(ctx)
      if (err instanceof CustomError) {
        const res = err.getCodeMsg()
        ctx.body = {}
        ctx.body.code = res.code || 500
        ctx.body.msg = res.msg
      } else if (err instanceof Error) {
        console.log(err)
        ctx.body = {}
        ctx.body.code = 500
        ctx.body.msg = err.message
      } else if (typeof err === 'string') {
        ctx.body = {}
        ctx.body.code = 500
        ctx.body.msg = err
      } else {
        ctx.body = {}
        ctx.body.code = res.code || 500
        ctx.body.msg = res.msg
      }
    }
  })


  app.router('addUser', async (ctx, next) => {
    const {
      openId,
      nickName,
      avatarUrl,
      occupation
    } = event.userInfo
    try {
      await db.collection('login')
        .where({
          openId: OPENID
        })
        .get().then(res => {
          if (res.data.length < 1) {
            db.collection('login').add({
              // data 字段表示需新增的 JSON 数据
              data: {
                // phone: event.userinfo.phone,
                nickName: nickName,
                avatarUrl: avatarUrl,
                openId: OPENID,
                occupation: occupation,
                time: new Date(),
              },
              success: function (res) {
                // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
                //对用户数据进行实时更新
                if (res) {
                  await db.collection("login").where({
                    openId: OPENID
                  }).update({
                    data: {
                      nickName: nickName,
                      avatarUrl: avatarUrl,
                      occupation: occupation,
                      _updateTime:new Date()
                    }
                  })
                }
                return ctx.body = {
                  res
                }
              }
            })
          }
        })
    } catch (error) {
      if (error instanceof CustomError) {
        throw error
      }
      if (error instanceof Error) {
        console.log(error)
        throw new CustomError(500, error.message)
      } else if (typeof error === 'string') {
        throw new CustomError(500, error)
      }
    }
  })

  // 查询用户的信息，并返回登录用户的信息
  app.router('findUser', async (ctx, next) => {
    const {
      openid
    } = event
    try {
      return await db.collection("login").where({
        openId: openid
      }
      ).get().then(res => {
        return ctx.body = {
          res
        }
      })
    } catch (e) {
      if (error instanceof CustomError) {
        throw error
      }
      if (error instanceof Error) {
        console.log(error)
        throw new CustomError(500, error.message)
      } else if (typeof error === 'string') {
        throw new CustomError(500, error)
      }
    }

  })
  return app.serve()
}